<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('销售订单明细列表')"/>
</head>
<script src="https://s3.pstatp.com/cdn/expire-1-M/jquery/3.3.1/jquery.min.js"></script>
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css"
      integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">

<!-- 可选的 Bootstrap 主题文件（一般不用引入） -->
<link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap-theme.min.css"
      integrity="sha384-6pzBo3FDv/PJ8r2KRkGHifhEocL+1X2rVCTTkUfGk7/0pbek5mMa1upzvWbrUbOZ" crossorigin="anonymous">

<!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
<script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js"
        integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd"
        crossorigin="anonymous"></script>
<style>
    body {
        font-family: Arial, sans-serif;
        background-color: #f0f0f0;
    }

    .container-div {
        max-width: 960px;
        margin: 0 auto;
        padding: 20px;
    }

    form {
        background-color: #fff;
        padding: 20px;
        border-radius: 8px;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    }

    table {
        width: 100%;
        margin-top: 20px;
        border-collapse: collapse;
    }

    table, th, td {
        border: 1px solid #ddd;
    }

    th, td {
        padding: 15px;
        text-align: left;
    }

    th {
        background-color: #4CAF50;
        color: white;
    }

    tr:nth-child(even) {
        background-color: #f2f2f2;
    }

    .btn {
        padding: 10px 20px;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        text-decoration: none;
    }

    .btn-primary {
        background-color: #007BFF;
        color: #fff;
    }

    .btn-primary:hover {
        background-color: #0056b3;
    }

    .btn-danger {
        background-color: #dc3545;
        color: #fff;
        margin-left: 10px;
    }

    .btn-danger:hover {
        background-color: #c82333;
    }
</style>
<body class="gray-bg">
<div class="container">
    <div class="row">
        <form class="form-horizontal">
            <div class="form-group">
                <label for="shop" class="col-sm-2 control-label">门店:</label>
                <div class="col-sm-10">
                    <select id="shop" class="form-control" required>
                        <option disabled selected>请选择门店</option>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label for="commodityType" class="col-sm-2 control-label">水果类型:</label>
                <div class="col-sm-10">
                    <select id="commodityType" class="form-control" required>
                        <option disabled selected>请先选择门店</option>
                    </select>
                </div>
            </div>

            <div class="form-group">
                <label for="commodityType1" class="col-sm-2 control-label">水果:</label>
                <div class="col-sm-10">
                    <select id="commodityType1" class="form-control" required>
                        <option disabled selected>请先选择水果类型</option>
                    </select>
                </div>
            </div>

            <div class="form-group">
                <label for="commodityDescription" class="col-sm-2 control-label">重量(kg):</label>
                <div class="col-sm-10">
                    <input type="text" id="commodityDescription" class="form-control" placeholder="数量" required>
                </div>
            </div>
        </form>
    </div>

    <div class="row">
        <form id="fruitForm" class="form-horizontal">
            <div class="form-group">
                <div class="col-sm-offset-2 col-sm-10">
                    <button type="button" class="btn btn-primary" id="saveButton">保存</button>
                </div>
            </div>
        </form>

        <table id="fruitTable" class="table table-striped table-bordered table-hover table-condensed text-center">
            <tr>
                <th>水果类型</th>
                <th>水果编号</th>
                <th>水果名称</th>
                <th>重量(kg)</th>
                <th>单价(500g)</th>
                <th>总价</th>
                <th>操作</th>
            </tr>
        </table>
        <div id="totalAmount" class="alert alert-info" role="alert"></div>
        <button id="alipay" class="btn btn-primary">确定</button>

        <button id="payButton" class="btn btn-success">支付</button>
    </div>
</div>
</body>
<script>
    let number = 0;
    //添加计数器计算商品数量
    let sum = 0;
    $(document).ready(function () {
        // 模块一：加载商店
        function loadShops() {
            $.ajax({
                url: "http://localhost:80/shop/list",
                dataType: "json",
                type: "get",
                success: function (resp) {
                    for (let i = 0; i < resp.length; i++) {
                        let store = resp[i];
                        $("<option></option>").val(store.sNumber).html(store.sName).appendTo("#shop");
                    }
                },
                error: function (xhr, type, errorThrown) {
                    console.log('XMLHttpRequest对象:', xhr);
                    console.log('错误类型:', type);
                    console.log('错误描述:', errorThrown);
                    alert("请求失败");
                }
            });
        }

        // 模块二：选择类型
        function selectType() {
            let type = $("#shop option:selected");
            console.log(type.val());
            $.ajax({
                url: "http://localhost:80/FruitTypes/inquireAll",
                dataType: "json",
                type: "get",
                data: {"shopId": type.val()},
                success: function (resp) {
                    console.log(resp)
                    $("#commodityType").empty();
                    if (resp.length !== 0) {
                        $("<option disabled></option>").html("请选择水果类型").appendTo("#commodityType");
                        for (let i = 0; i < resp.length; i++) {
                            let fruits = resp[i];
                            console.log(fruits.code);
                            console.log(fruits.name)
                            $("<option></option>").val(fruits.code).html(fruits.name).appendTo("#commodityType");
                        }
                    } else {
                        $("<option disabled></option>").html("无").appendTo("#commodityType");
                    }

                },
                error: function (xhr, type, errorThrown) {
                    alert("请求失败");
                }
            });
        }

        // 模块三：选择水果
        function sendRequest() {
            let code = $("#commodityType").val();
            console.log(code);
            $.ajax({
                url: "http://localhost:80/inventory/fruits/inquireByFruittypesId",
                dataType: "json",
                type: "post",
                data: {"fruittypesId": code},
                success: function (resp) {
                    console.log(resp)
                    $("#commodityType1").empty();
                    if (resp) {
                        $("<option disabled></option>").html("请选择水果").appendTo("#commodityType1");
                        for (let i = 0; i < resp.length; i++) {
                            let fruits = resp[i];
                            //查询库存
                            $.ajax({
                                url: "http://localhost:80/Fruits/number",
                                dataType: "json",
                                type: "post",
                                contentType: "application/json",
                                data: JSON.stringify({
                                    "fruittypesId": code,
                                    "fruitId": fruits.code
                                }),
                                success: function (resp) {
                                    if (resp > 0) {
                                        $("<option></option>")
                                            .val(fruits.code)
                                            .html(fruits.name)
                                            .data('stock', resp)
                                            .appendTo("#commodityType1");
                                        number = resp;
                                    } else {
                                        console.log("库存不足")
                                    }
                                }
                            });
                        }
                    } else {
                        console.log('查询失败');
                    }
                },
                error: function (xhr, type, errorThrown) {
                    alert("请求失败");
                }
            });

        }

        // 调用模块
        loadShops();

        $("#shop").change(function () {
            $("#commodityType1").empty();
            $("<option disabled></option>").html("请先选择水果类型").appendTo("#commodityType1");
            selectType();
        });

        $("#commodityType").change(function () {
            sendRequest();
        });
    });
    let stock = $('#commodityType1 option:selected').data('stock');
    console.log(name, stock);


    let totalAmountValue; // 声明全局变量
    document.getElementById('saveButton').addEventListener('click', function () {
        let type = $("#commodityType option:selected");
        let typeVal = type.val();
        console.log(typeVal);
        console.log(type.text());
        console.log(type);
        let fruit = $("#commodityType1 option:selected");
        let fruitVal = fruit.val();
        var quantity = document.getElementById('commodityDescription').value;

        // 检查这三个值是否都存在
        if (type.text() && fruit.text() && quantity) {
            var i = $("#shop option:selected").val();
            $.ajax({
                url: 'http://localhost:80/priceFruitPrice/getPriceByCode',
                type: 'GET',
                data: {
                    "sNumber": i,
                    code: fruitVal
                },
                success: function (data) {
                    let price = data;

                    var table = document.getElementById('fruitTable');
                    var found = false;
                    // 遍历表格的每一行，检查是否已经存在相同的水果
                    $("#fruitTable tr").each(function () {
                        if ($(this).find("td").eq(2).text() === fruit.text()) {
                            // 如果存在，更新重量和总价
                            var oldQuantity = parseFloat($(this).find("td").eq(3).text());
                            var newQuantity = oldQuantity + parseFloat(quantity);
                            stock = stock - quantity;
                            $(this).find("td").eq(3).text(newQuantity.toFixed(2)); // 使用toFixed(2)来保留两位小数
                            $(this).find("td").eq(5).text((price * newQuantity).toFixed(2));
                            found = true;
                            sum = sum+1;
                        }
                    });
                    if (!found) {
                        // 如果不存在，添加新的一行
                        var row = table.insertRow(-1);
                        row.insertCell(0).innerHTML = type.text(); // 水果类型
                        row.insertCell(1).innerHTML = fruitVal; // 水果编号
                        row.insertCell(2).innerHTML = fruit.text(); // 水果名称
                        row.insertCell(3).innerHTML = quantity; //重量
                        stock = stock - quantity;
                        row.insertCell(4).innerHTML = price; // 单价
                        row.insertCell(5).innerHTML = ((price * 2) * quantity).toFixed(2); // 总价
                        var deleteButton = document.createElement('button');
                        deleteButton.textContent = '删除';
                        deleteButton.addEventListener('click', function () {
                            table.deleteRow(row.rowIndex);
                            calculateTotalAmount(); // 在删除表格行后，重新计算总金额
                            sum = sum+1;
                        });
                        row.insertCell(6).appendChild(deleteButton); // 操作
                    }

                    calculateTotalAmount(); // 在添加新行到表格后，重新计算总金额
                },
                error: function (error) {
                    console.log('发生错误: ', error);
                }
            });

        } else {
            console.log('请确保所有值都已输入');
        }
    });

    // 计算总金额
    function calculateTotalAmount() {
        var totalAmount = 0;
        $("#fruitTable tr").each(function () {
            var price = $(this).find("td").eq(5).text();
            if (price) {
                totalAmount += parseFloat(price);
            }
        });

        // 显示总金额，格式化为两位小数
        totalAmountValue = totalAmount.toFixed(2);
        document.getElementById('totalAmount').innerHTML = "总金额: " + totalAmountValue;
    }

/*---------------------------------------------------------------------------------------------*/
    //点击确定生成支付二维码
    document.getElementById('alipay').addEventListener('click', function () {
        //店名
        var firstOptionText = $("#shop option:first").text();
        console.log(firstOptionText);
        //获取总金额
        var totalAmountText = document.getElementById('totalAmount').innerHTML;
        var totalAmountValue = totalAmountText.split(": ")[1];
        //商品数量
        // 创建一个对象来存储你想要发送的数据
        var dataToSend = {
            shopName: firstOptionText,
            totalAmount: totalAmountValue,
            quantity: sum,
        };

        $.ajax({
            url: 'http://localhost:80/salesorderdetails/alipay',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(dataToSend),
            success: function (response) {
                console.log('成功: ', response);

                // 检查响应数据中的第二个元素是否为"异常"
                if (response[1] === "异常") {
                    // 如果出现异常，显示一个弹窗
                    alert("支付失败");
                } else {
                    // 如果没有出现异常，显示模态框
                    var orderNumber = response[0];
                    var filePath = response[1];

                    // 创建一个模态框
                    var modal = document.createElement("div");
                    modal.setAttribute("class", "modal");

                    // 在模态框中显示订单号和图片
                    modal.innerHTML =
                        "<div class='modal-content'>" +
                        "<h2>订单号: " + orderNumber + "</h2>" +
                        "<img src='" + filePath + "' alt='QR Code'>" +
                        "</div>";

                    // 将模态框添加到页面中
                    document.body.appendChild(modal);
                }
            },
            error: function (error) {
                console.log('发生错误: ', error);
                location.reload();
            }
        });
    });
    /*------------------------------------------------------------------------------------*/
    // 添加支付按钮的点击事件
    document.getElementById('payButton').addEventListener('click', function () {
        // 创建一个数组来存储所有的水果数据
        var fruits = [];
        var i = $("#shop option:selected").val();
        console.log("店名", i)
        // 遍历表格的每一行，获取每个水果的数据
        $("#fruitTable tr").each(function (index) {
            // 跳过表头
            if (index === 0) return;
            var fruit = {};
            fruit.fruitpriceId = $(this).find("td").eq(1).text(); // 水果编号
            fruit.count = $(this).find("td").eq(3).text(); // 重量
            fruit.money = $(this).find("td").eq(4).text(); // 单价
            fruit.totalmoney = totalAmountValue; // 总价
            fruit.sId = i;
            fruits.push(fruit);
        });

        fruits.forEach(function (fruit) {
            console.log("==============", fruit.sId);
        });
        console.log(JSON.stringify(fruits))
        if (fruits.length > 0) {
            $.ajax({
                url: 'http://localhost:80/salesorderdetails/insert', // 你的后端接口地址
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(fruits), // 将水果数据转换为JSON格式

                success: function (response) {
                    console.log('成功: ', response);
                    alert("成功");
                    location.reload();
                },
                error: function (error) {
                    console.log('发生错误: ', error);
                    location.reload();
                }
            });
        } else {
            alert("没有订单");
            location.reload();
        }
    });


</script>
</html>